package net.system.sys.action;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.core.base.struts.BaseAction;
import net.core.common.Constants;
import net.core.common.HttpUtil;
import net.core.common.StrUtils;
import net.core.service.encrype.MD5;
import net.sf.json.JSONObject;
import net.system.base.bean.SSysuser;
import net.system.common.Common;
import net.system.common.Utils;
import net.system.sys.service.ILoginService;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;


@Scope("request")
@Namespace("/system/login")
@InterceptorRefs(@InterceptorRef("basicStack"))
@ParentPackage("struts-default")
@Results({ @Result(name = "error", location = "/login.jsp") })
public class LoginAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private ILoginService service;

	private String userId;
	private String password;
	private String error;
	
	private String suRm;
	
	private List<Map> moduleList;

	@Action(value = "login", results = { @Result(name = "success", location = "/WEB-INF/pages/system/main/Main.jsp") })
	public String login() {
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();

		// 判断校验码
		String reg = (String) request.getParameter("regCode");
		String sessionReg = (String) session.getAttribute("reg");
		if (regCheck(reg, sessionReg)) {
			return ERROR;
		}
		clearSession();
		System.out.println("login user:"+userId);
		SSysuser user = service.getLoginUser(userId);
		Utils.beanToString(user);
		if (user != null) {
			MD5 md5 = new MD5();
			// 密码验证
			System.out.println(" user pwd:"+password);
			String intoPassword = md5.getMD5ofStr(userId.toUpperCase() + password);
			// System.out.println(intoPassword);
			if (!intoPassword.equals(user.getSuPwd())) {
				error = "2";
				return ERROR;
			}
			service.setSessionAttribute(session, user);
		}
		//读取用户的权限
		System.out.println(" user type:"+user.getSuType());
		loadUserModule(user.getSuType());
		for(int i=0;i<moduleList.size();i++){
			Map map = moduleList.get(i);
			System.out.println(map.toString());
		}
		return SUCCESS;
	}
	
	private void loadUserModule(String suType) {
		// TODO 根据用户类型获取相关的模块
		// 用户类型#0-普通用户，1-代理商，2-系统管理，3-超级管理
		moduleList = service.getUserModule(suType);
		//getRequest().setAttribute("moduleList", list);
	}

	@Action(value = "reg", results = { @Result(name = "success", location = "/WEB-INF/pages/system/main/Reg.jsp") })
	public String reg() {
		// 用户注册
		return SUCCESS;
	}
	
	@Action(value = "saveReg", results = { @Result(name = "success", location = "/WEB-INF/pages/system/main/RegSucc.jsp") })
	public String saveReg() {
		// 用户注册
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();

		// 判断校验码
		String reg = (String) request.getParameter("regCode");
		String sessionReg = (String) session.getAttribute("reg");
		if (regCheck(reg, sessionReg)) {
			return ERROR;
		}
		// 校验密码是否一致
		String pwd = (String) request.getParameter("suPwd");
		String pwd1 = (String) request.getParameter("suPwd1");
		if(!pwd.equals(pwd1)){
			error = "7";
			return ERROR;
		}
		
		// 保存数据
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		System.out.println(reqMap.toString());
		service.saveUser(reqMap);
		
		return SUCCESS;
	}
	
	@Action(value = "logOut", results = { @Result(name = "success", location = "/login.jsp") })
	public String logOut() {
		// 清空session
		clearSession();

		String error = getRequest().getParameter("error");
		if (StrUtils.isNotNull(error)) {
			getRequest().setAttribute("error", error);
		}

		return "success";
	}
	
	@Action(value = "checkForm")
	public String checkForm() {
		//
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();

		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		
		String s = service.checkUser(reqMap);
		HttpServletResponse response = getResponse();
		JSONObject json = new JSONObject();
		json.put("value", s);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding(Constants.SYS_ENCODE);
			out = response.getWriter();
			out.print(json);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}

		return SUCCESS;
	}

	private boolean regCheck(String reg, String sessionReg) {
		if (reg == null || "".equals(reg)) {
			error = "5";
			return true;
		}
		if (!reg.equals(sessionReg)) {
			error = "6";
			return true;
		}
		return false;
	}

	private void clearSession() {
		HttpSession session = getSession();
		session.removeAttribute(Common.USER_SESSION);
		session.setAttribute(Common.USER_SESSION, null);
		session.removeAttribute(Common.USER_SESSION_ORG);
		session.setAttribute(Common.USER_SESSION_ORG, null);
		// System.out.println("logout......");
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public List<Map> getModuleList() {
		return moduleList;
	}

	public void setModuleList(List<Map> moduleList) {
		this.moduleList = moduleList;
	}

	public String getSuRm() {
		return suRm;
	}

	public void setSuRm(String suRm) {
		this.suRm = suRm;
	}

}
